import pymysql

# 配置单独
DB_CONFIG = {
    "host": "localhost",
    "user": "root",
    "password": "123456",
    "database": "wotu_ods",
    "port": 3306
}


def get_connection():
    try:
        conn = pymysql.connect(**DB_CONFIG)  # 关键字读取,6
        print('✅ 连接数据库成功')
        return conn
    except Exception as e:
        print(f'❌ 连接数据库失败: {e}')
        return None


def insert_data_to_hub(records: list, table_name: str, batch_size: int = 5000):
    """
    :param records:  SQL语句的 list
    :param table_name: 表名
    """
    conn = get_connection()
    if not conn:
        return

    cursor = conn.cursor()
    count = 0
    fail_count = 0
    try:
        # i从1开始
        for i, sql in enumerate(records, start=1):
            try:
                cursor.execute(sql)
                count += 1
            except Exception as e:
                fail_count += 1
                print(f"⚠️ 插入失败: {e}\nSQL: {sql}")

            #     批量提交
            if i % batch_size == 0:
                conn.commit()  # ✅ 批量提交，减少IO

        #  剩下的单独提交
        conn.commit()

    except Exception as e:
        conn.rollback()
        print(f"❌ 批量插入失败: {e}")
    finally:
        cursor.close()
        conn.close()

    print(f'✅ 总共往 {table_name} 写入 {count} 条数据,失败条数{fail_count}')


if __name__ == '__main__':
    # demo
    test_records = [
        "INSERT INTO test_table (id, name) VALUES (1, 'Tom');",
        "INSERT INTO test_table (id, name) VALUES (2, 'Jerry');"
    ]
    insert_data_to_hub(test_records, "test_table")
